<?php
namespace App\Http\Controllers\FrontEnd;

use App\Http\Controllers\Controller;
use App\Models\MAddress;
use App\Models\MArea;
use App\Models\MExpressCompany;
use App\Models\MOrder;
use App\Models\MProduct;
use App\Models\MUser;
use App\Models\MUserAttr;
use App\Models\MWallet;
use App\Utils\ShoppingCar;
use DB;
use Illuminate\Http\Request;

/**
 * 在线购物商城控制器
 */
class ProductController extends Controller
{
    /**
     * 购物中心界面
     */
    public function productsPage(Request $request, $index = 1)
    {
        $this->fyInit(route('web.products'), 16)->fyCalc(MProduct::where('status', MProduct::$STATUS_SALE)->count(), $index);
        $this->data['products'] = MProduct::where('status', MProduct::$STATUS_SALE)->skip($this->fy_pgOffset)->take($this->fy_pgSize)->get();
        $this->fyViewInit($this->data);
        return view("web.products")->with($this->data);
    }

    /**
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function productDetail(Request $request, $id = 0)
    {
        $id = $request->id;
        $this->data['product'] = MProduct::where('id', $id)->where('status', MProduct::$STATUS_SALE)->first();
        $this->data['user_addr'] = MAddress::where('uid', ss('uid'))->first();
//        dd($this->data['user_addr']);
        $this->data['user'] = MUser::find(ss('uid'));
        return view("web.product_detail")->with($this->data);
    }

    /**
     * 加入商品到购物车
     */
    public function addCart(Request $request)
    {
        if (cv("switch.shopping") == 0) {
            $this->data = $this->makeJsCode(1, "该功能暂时关闭！");
            return response()->json($this->data);
        }

        if (!$request->has(['no', 'buy-num'])) {
            $this->data = $this->makeJsCode(1, "数据验证失败！");
            return response()->json($this->data);
        }

        if (!is_numeric($request->input('buy-num')) || $request->input('buy-num') <= 0) {
            $this->data = $this->makeJsCode(1, "加入失败，请选择大于0的商品数量！");
            return response()->json($this->data);
        }

        $car = new ShoppingCar();
        if ($car->add($request->no, $request->input("buy-num"))) {
            $this->data = $this->makeJsCode(0, "加入成功！");
        } else {
            $this->data = $this->makeJsCode(1, "加入失败！");
        }
        return response()->json($this->data);
    }

    /**
     * 删除购物车里面的商品
     */
    public function delCart($no)
    {
        $no = json_decode($no);

        $car = new ShoppingCar();

        $flag = true;
        foreach ($no as $item) {
            if (!$car->del($item)) {
                $flag = false;
                break;
            }
        }

        if ($flag) {
            $this->data = $this->makeJsCode(0, "删除成功！");
        } else {
            $this->data = $this->makeJsCode(1, "删除失败！");
        }
        return response()->json($this->data);
    }

    /**
     * 购物车页面
     */
    public function cartsPage()
    {
        $car = new ShoppingCar();
        $this->data['carts'] = MProduct::whereIn('no', $car->no())->get();
        $this->data['cart'] = $car->cart;
        $this->data['total'] = $car->calc();
//        dd($this->data['cart']);
        return view("web.carts")->with($this->data);
    }

    /**
     * 购物车结算操作
     */
    public function orderCreate(Request $request)
    {
        $product_ids = trim($request->product_ids, ',');
        $product_nos = trim($request->product_nos, ',');
        $buy_nums = trim($request->buy_nums, ',');

        if (cv("switch.shopping") == 0) {
            $this->data = $this->makeJsCode(1, "该功能暂时关闭！");
            return response()->json($this->data);
        }

        if (empty($product_ids) || empty($product_nos) || empty($buy_nums)) {
            $this->data = $this->makeJsCode(1, "订单信息有误！");
            return response()->json($this->data);
        }

        //检查二级密码
        $user = MUser::find(ss('uid'));
        if (!$request->has('safepass') || $request->safepass !== $user->safepass) {
            $this->data = $this->makeJsCode(1, "支付密码错误！");
            return response()->json($this->data);
        }

        //判断是否有收货地址
        $addr = MAddress::where('uid', ss('uid'))->first();
        if (empty($addr)) {
            $this->data = $this->makeJsCode(1, "请先完善您的收货地址再进行结算！");
            return response()->json($this->data);
        }

        //检查商品是否存在
        $ids = explode(',', $product_ids);
        $nos = explode(',', $product_nos);
        $nums = explode(',', $buy_nums);
        $total_price = 0;

        foreach ($ids as $k => $pid) {
            $pro = MProduct::where('id', $ids[$k])->where('no', $nos[$k])->first();
            if (empty($pro)) {  //检查商品是否存在
                $this->data = $this->makeJsCode(1, "商品信息有误！");
                return response()->json($this->data);
            }

            $nums[$k] = intval($nums[$k]);

            if (empty($nums[$k]) || !is_numeric($nums[$k]) || $nums[$k] <= 0) {
                $this->data = $this->makeJsCode(1, "商品选购数量异常！");
                return response()->json($this->data);
            }

            if ($nums[$k] > $pro->num) {    //检查商品库存是否不足
                $this->data = $this->makeJsCode(1, "所选商品 {$pro->title} 库存不足，无法满足订购数量！");
                return response()->json($this->data);
            }
            $total_price += $pro['p1'] * intval($nums[$k]); //计算商品总价
        }

        //检查商品总价是否和传来的值一致
        if (floatval($total_price) !== floatval($request->payMoney)) {
            $this->data = $this->makeJsCode(1, "订单金额信息有误！");
            return response()->json($this->data);
        }

        //检查钱包余额是否充足
        $me_wallet = $user->wallet;
        $request_wallet = $request->wallet; //支付的钱包类型
        $request_money = $request->payMoney; //应该支付的金额

        if ($request_wallet == MWallet::$WALLET_TYPE_1 && sprintf("%.2f", $request_money) > sprintf("%.2f", $me_wallet->w1)) {

            $msg = "购买失败," . uWalletStr(MWallet::$WALLET_TYPE_1) . "余额不足!";

            $this->data = $this->makeJsCode(1, $msg);
            return response()->json($this->data);
        } elseif ($request_wallet == MWallet::$WALLET_TYPE_2 && sprintf("%.2f", $request_money) > sprintf("%.2f", $me_wallet->w2)) {

            $msg = "购买失败," . uWalletStr(MWallet::$WALLET_TYPE_2) . "余额不足!";

            $this->data = $this->makeJsCode(1, $msg);
            return response()->json($this->data);
        } elseif ($request_wallet == MWallet::$WALLET_TYPE_3 && sprintf("%.2f", $request_money) > sprintf("%.2f", $me_wallet->w3)) {

            $msg = "购买失败," . uWalletStr(MWallet::$WALLET_TYPE_3) . "余额不足!";

            $this->data = $this->makeJsCode(1, $msg);
            return response()->json($this->data);
        }

        DB::transaction(function () use (&$user, &$me_wallet, &$request, &$product_ids, &$product_nos, &$buy_nums) {

            if ($me_wallet->buyShop($request->wallet, $request->payMoney) && MOrder::webCreateOrder($user, $product_ids, $product_nos, $request->payMoney, $buy_nums, $request->detail)) {

                $this->data = $this->makeJsCode(0, "支付成功！");
            } else {
                DB::rollBack();
                $this->data = $this->makeJsCode(1, "支付失败！");
            }

        });

        return response()->json($this->data);
    }

    /**
     * 我的订单列表页面
     */
    public function ordersPage(Request $request, $index = 1)
    {
        $query = (new MOrder())->query();
        $query = $query->where('uid', ss('uid'));

        $type = intval($request->type);
        if (!empty($type) && !empty($request->search)) {
            if ($type == 1) {
                $query = $query->where("no", $request->search);
            }
        }

        $this->fyInit(route('web.orders'), 15)->fyCalc($query->count(), $index);
        $orders = $query->get();
        foreach ($orders as &$order) {
            $good_ids = explode(',', $order->good_id);
            $good_nos = explode(',', $order->good_no);
            $good_nums = explode(',', $order->num);

            $good_info_str = '';
            foreach ($good_ids as $k => $good_id) {
                $good = MProduct::where("id", $good_ids[$k])->where('no', $good_nos[$k])->first();
                if (!$good) {
                    throw new Exception("未查找到相关商品");
                }
                $good_name = $good->title;
                $good_link = route('web.product_detail', ['id' => $good_ids[$k]]);
                $good_info_str .= "<span onclick='window.open(\"$good_link\")' style='cursor:pointer;color: green;'>$good_name</span> * $good_nums[$k]<br>";
            }
            $order->good_info = $good_info_str;
        }
        $this->data['orders'] = $orders;
        $this->fyViewInit($this->data);
        return view("web.shopping_logs")->with($this->data);
    }

    /**
     * CURL获取物流信息
     * @param $oid  订单ID
     * @return \Illuminate\Http\JsonResponse
     */
    public function expressInfo($oid)
    {
        $order = MOrder::find($oid);
        $express_company = MExpressCompany::find($order->express_company_id);
        $short_name = $express_company->alias; //快递公司简称
        $no = $order->express_no;

        $curl = curl_init();
        //设置选项，包括URL
        curl_setopt($curl, CURLOPT_URL, "http://www.kuaidi100.com/query?type=" . $short_name . "&postid=" . $no);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $this->data['data'] = curl_exec($curl);
        //释放curl句柄
        curl_close($curl);
        $this->data['express'] = $express_company;
        return response()->json($this->data);
    }

    /**
     * 我的收货地址页面
     */
    public function addressPage()
    {
        $this->data['my_addr'] = MAddress::where('uid', ss('uid'))->first();
//        dd($this->data['my_addr']);
        $this->data['provinces'] = MArea::where('parent_id', 0)->get();
        return view("web.address")->with($this->data);
    }

    /**
     * @param Request $request
     * 三级联动
     */
    public function addressChange(Request $request)
    {
        $id = $request->id;
        $array_citys = MArea::where('parent_id', $id)->get();
        $str = '';
        foreach ($array_citys as $array_city) {
            $str .= "<option value=" . $array_city->id . ">" . $array_city->name . "</option>";
        }

        echo $str;
    }


    /**
     * 收货地址存储请求
     */
    public function addrSave(Request $request)
    {
//        if (count($request->rule) > 0) {//验证自动添加的属性规则
//            for ($i = 0; $i < count($request->rule); $i++) {
//                $rule = unserialize($request->rule[$i]);
//                $msg = unserialize($request->msg[$i]);
//                if (!$this->validateReq($request, $rule, $msg)) {
//                    $this->data = $this->makeJsCode(1, $this->errors->first());
//                    return response()->json($this->data);
//                }
//            }
//        }
        if (!$this->validateReq($request, MAddress::saveRulesWithMsg(0), MAddress::saveRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }

//        if (MAddress::saveAddress($request, ss('uid')) && MUserAttr::userInfo(ss('uid'), $request->all())) {
        if (MAddress::saveAddress($request, ss('uid'))) {
            $this->data = $this->makeJsCode(0, "保存成功！");
        } else {
            $this->data = $this->makeJsCode(1, "保存失败！");
        }
        return response()->json($this->data);
    }
}